//
//  NetworkTools.swift
//  SinaWebo
//
//  Created by mis on 16/3/20.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit
import AFNetworking

private let hostname = "https://api.weibo.com/"
private let weiboDomain = "com.baidu.data.error"
enum HTTPMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    /// 单例
    static let sharedTools: NetworkTools = {
        let url = NSURL(string: hostname)
        let network = NetworkTools(baseURL: url)
        network.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return network
    }()
    
    /// 加载数据
    func requestJsonDict(method: HTTPMethod, urlString : String, parameters: [String : AnyObject]?, finished: (result:[String : AnyObject]?, error: NSError?) -> ()) {
        if method == HTTPMethod.GET {
            GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                if let dict = result as? [String: AnyObject] {
                    finished(result: dict, error: nil)
                    return
                }
                let error = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedFailureReasonErrorKey: "数据错误"])
                finished(result: nil, error: error)
                }, failure: { (_, error) -> Void in
                    print(error.userInfo[NSLocalizedFailureReasonErrorKey])
                    finished(result: nil, error: error)
            })
        }else {
            POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                if let dict = result as? [String : AnyObject] {
                    finished(result: dict, error: nil)
                    return
                }
                let error = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedFailureReasonErrorKey: "数据错误"])
                finished(result: nil, error: error)
                }, failure: { (_, error) -> Void in
                    print(error.userInfo[NSLocalizedFailureReasonErrorKey])
                    finished(result: nil, error: error)
            })
        }
    }
    
    /// 加载图片
    func uploadImage(urlString: String, parameters: [String : AnyObject]? , imageData: NSData, finished:(result: [String : AnyObject]?, error: NSError?) -> ()) {
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (data) -> Void in
            data.appendPartWithFileData(imageData, name: "pic", fileName: "image.png", mimeType: "image/jpeg")
            }, progress: nil, success: { (_, result) -> Void in
                if let dict = result as? [String: AnyObject] {
                    finished(result: dict, error: nil)
                }
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }
}
